const log = require('../../util/log')
const {
  Network,
  Page,
  DOM,
  Runtime,
  Emulation
} = require('../chromeMng.20180824').client;

async function getTaobaoKeyWords() {
  log('getting taobao key words')
  await Page.navigate({
    url: 'https://top.taobao.com/index.php'
  })
  return step2()
}

async function step2() {
  log('getting taobao key words step 2')
  var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".more")'})
  var cnt = result.description.substring(9, result.description.length - 1)
  if (cnt != 2) {
    return new Promise(resolve => {
      setTimeout(() => {
        step2().then(result => {
          resolve(result)
        })
      }, 1000)
    })
  }
  await Runtime.evaluate({expression: 'document.querySelectorAll(".more")[0].click()'})
  return step3()
}

async function step3() {
  log('getting taobao key words step 3')
  var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".title")'})
  var cnt = result.description.substring(9, result.description.length - 1)
  if (cnt != 20) {
    return new Promise(resolve => {
      setTimeout(() => {
        step3().then(result => {
          resolve(result)
        })
      }, 1000)
    })
  }
  var keyWords = []
  for (var i = 0; i < cnt; i++) {
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".title")[' + i + '].innerText'})
    keyWords.push(result.value)
  }
  return new Promise(resolve => {
    resolve(keyWords)
  })
}

module.exports = getTaobaoKeyWords
